import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, Form, message, Input, DatePicker, Select, InputNumber } from 'antd';
import PropTypes from 'prop-types';
import moment from 'moment';
import { getDictOptionsByCode } from '@/support/common';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  VehicleMng: state.VehicleMng,
});
class BindModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.object,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      handheldsCodeOption: [],
      cboxCodeOption: [],
    };
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, formData } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      this.getInitData();
      this.formRef &&
        this.formRef.current?.setFieldsValue({
          vin: formData.vin,
        });
    }
  }

  handleSubmit = () => {
    this.formRef.current?.submit();
  };

  onFinish = async (values: any) => {
    const { dispatch, formData, freshPage, closeModal } = this.props;
    let postData = {
      ...values,
    };
    this.setState({
      loading: true,
    });
    const params = {
      vin: formData.vin,
      handheldsCode: postData.handheldsCode,
      cboxCode: postData.cboxCode,
    };
    dispatch({
      type: 'VehicleMng/postObjWithRes',
      payload: { url: '/msalcohollock/vehicle/bind/device', ...params },
      callback: (res: any) => {
        this.setState({
          loading: false,
        });
        this.setState({
          loading: false,
        });
        if (res.statusCode === '0') {
          message.success('绑定成功');
          this.close();
          freshPage();
        } else if (res.statusCode !== '1001002') {
          message.warning('绑定失败，请重试');
        }
      },
    });
    // const promise0 = dispatch({
    //   type: 'VehicleMng/getData',
    //   payload: { url: `/msalcohollock/cbox/binding/state/${postData.cboxCode}` },
    //   callback: (res: any) => {
    //     if (res.statusCode !== '0') {
    //       message.warning('控制盒已被其他车辆绑定');
    //     }
    //   },
    // });
    // const promise1 = dispatch({
    //   type: 'VehicleMng/getData',
    //   payload: { url: `/msalcohollock/handhelds/binding/state/${postData.handheldsCode}` },
    //   callback: (res: any) => {
    //     if (res.statusCode !== '0') {
    //       message.warning('手持机已被其他车辆绑定');
    //     }
    //   },
    // });
    // Promise.allSettled([promise0, promise1])
    //   .then(results => {
    //     this.setState({
    //       loading: true,
    //     });
    //     if (results.every(t => t.value.statusCode === '0')) {
    //       const params = {
    //         vin: formData.vin,
    //         handheldsCode: postData.handheldsCode,
    //         cboxCode: postData.cboxCode,
    //       };
    //       dispatch({
    //         type: 'VehicleMng/postObjWithRes',
    //         payload: { url: '/msalcohollock/vehicle/bind/device', ...params },
    //         callback: (res: any) => {
    //           this.setState({
    //             loading: false,
    //           });
    //           if (res.statusCode === '0') {
    //             message.success('绑定成功')
    //             this.close();
    //             freshPage();
    //           }else{
    //             message.warning('绑定失败，请重试')
    //           }
    //         },
    //       });
    //     } else{
    //       this.setState({
    //         loading: false,
    //       });
    //     }
    //   })
    //   .catch(() => {
    //     this.setState({
    //       loading: false,
    //     });
    //   });
  };

  close = () => {
    const { closeModal } = this.props;
    this.formRef.current && this.formRef.current.resetFields();
    closeModal();
  };
  getInitData = () => {
    const { dispatch } = this.props;

    dispatch({
      type: 'VehicleMng/getData',
      payload: {
        url: '/msalcohollock/cbox/user/list',
        code: '',
      },
      callback: res => {
        this.setState({
          cboxCodeOption: res.data?.map(t => ({ label: t.code, value: t.code })) ?? [],
        });
      },
    });
    dispatch({
      type: 'VehicleMng/getData',
      payload: {
        url: '/msalcohollock/handhelds/user/list',
        code: '',
      },
      callback: res => {
        this.setState({
          handheldsCodeOption: res.data?.map(t => ({ label: t.code, value: t.code })) ?? [],
        });
      },
    });
  };
  ok = () => {
    const { dispatch } = this.props;
  };
  render() {
    const { formData, modalVisible } = this.props;
    const { loading, cboxCodeOption, handheldsCodeOption } = this.state;
    const burningStatus = getDictOptionsByCode(this.context.dicData, 'burningStatus');
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.handleSubmit} type="primary">
          确定
        </Button>
      </div>
    );
    let title = '新增车辆';

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: {
          span: 6,
          // offset: 4,
        },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: {
          span: 14,
        },
        md: { span: 16 },
      },
    };

    return (
      <Modal
        title={'绑定设备'}
        footer={footer}
        visible={modalVisible}
        width={700}
        onCancel={this.close}
        onOk={this.ok}
      >
        <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.onFinish}>
          <FormItem
            {...formItemLayout}
            label="VIN"
            colon={false}
            name="vin"
            rules={[
              {
                required: true,
                message: '请输入VIN,只能输入大写英文及数字',
                whitespace: true,
                pattern: /^[A-Za-z0-9]+$/,
              },
            ]}
            normalize={(value, prevValue, prevValues) => {
              // 转大写
              return value.toUpperCase();
            }}
          >
            <Input
              style={{ textTransform: 'uppercase' }}
              disabled={!!formData.vin}
              placeholder="请输入VIN"
              maxLength={17}
            />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="控制盒编号"
            colon={false}
            name="cboxCode"
            rules={[{ required: true, message: '请选择控制盒编号' }]}
          >
            <Select
              options={cboxCodeOption}
              placeholder="请设选择控制盒编号"
              showSearch
              allowClear
              // getPopupContainer={triggerNode => triggerNode.parentNode}
            ></Select>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="手持机编号"
            colon={false}
            name="handheldsCode"
            rules={[{ required: true, message: '请选择手持机编号' }]}
          >
            <Select
              options={handheldsCodeOption}
              placeholder="请设手持机编号"
              allowClear
              showSearch
              // getPopupContainer={triggerNode => triggerNode.parentNode}
            ></Select>
          </FormItem>
        </Form>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(BindModal);
